//
//  File.swift
//  
//
//  Created by ellzu gu on 2021/9/2.
//

import Foundation


public class Dispatch {
    let root: String
    public var welcome: String = "index.html"
    public var notFound: String = "404.html"
    public init(_ root: String) {
        self.root = root
    }
    
    public func request(_ request: PathRequest) -> InputPacket {
        
        let path = (request.path as NSString).lastPathComponent.count == 0 ? (request.path as NSString).appendingPathComponent(self.welcome) : request.path
        let filePath = self.filePath(path)
        
        if let file = FileHandle(forReadingAtPath: filePath) {
            let packet = FilePacket(file)
            return packet
        }
        
        let notFountPath = self.filePath(self.notFound)
        if let file = FileHandle(forReadingAtPath: notFountPath) {
            let packet = FilePacket(file)
            return packet
        }
        
        var parameter: [String : Any] = [:]
        parameter["code"] = 404
        let packet = DataPacket.packet(parameter)!
        return packet
        
    }
    
    public func filePath(_ namePath: String) -> String {
        return (self.root as NSString).appendingPathComponent(namePath)
    }
}

extension Dispatch {
    public static let shared = Dispatch( (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("www"))
}
